package com.newworld.dmsapp2.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.serviceapply.ChoosephotoActivity;
import com.newworld.dmsapp2.activity.serviceapply.ViewPagerActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.bean.UserAccount;
import com.newworld.dmsapp2.fragment.MainSettingFragment;
import com.newworld.dmsapp2.ui.view.CustomEditDialog;
import com.newworld.dmsapp2.ui.view.CustomEditSexDialog;
import com.newworld.dmsapp2.ui.view.CustomEditSexDialog.OnStateChagedListener;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.GetFileSize;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

@SuppressLint("ResourceAsColor")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class SettingAccountActivity extends BaseActivity implements
		OnClickListener {
	private LinearLayout ly_set_name_edit, ly_set_sex_edit, ly_set_birth_edit,
			ly_set_tellphone_edit, ly_set_email_edit, ly_set_person_portrait;
	private LinearLayout ly_set_account_depart, ly_set_account_position,
			ly_set_account_edit_modify_password;

	private ImageButton titlebar_left_account_return;
	private ImageView person_portrait_girl;
	private EditText nameEdit, sexEdit, birthEdit, tellphoneEdit, emailEdit;
	private TextView usernameTx;
	private User user;
	private UserAccount useraccount;
	private TextView set_account_position_who,set_account_depart;
	private ProgressBar logInbar;
	public static String str, text, text1, text2, lol1, lol2;
	private long l1, l2, k;
	// 图像选择所需参数
	private String imageRealPath11 = "";
	private Uri imageUri;
	private String imagePath11 = "";
	public static int flag = 0;
	private String username = null;
	
	@SuppressWarnings("unused")
	private String userRealnamestr,userSexstr,userBirthstr,userPhonestr,userEmailstr;
	public static final DisplayImageOptions options = new DisplayImageOptions.Builder()

	.cacheInMemory(false) // 设置下载的图片是否缓存在内存中
			.cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565) // 设置下载的图片是否缓存在SD卡中
			.displayer(new RoundedBitmapDisplayer(50)) // 设置成圆角图片
			.build();

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Config.HANDLER_MSG_EDITPERSON_SUCCESS://上传个人设置成功
				logInbar.setVisibility(View.GONE);
				user = SingleSample.getInstance(SettingAccountActivity.this).getUser();
				useraccount = user.getUseraccounts().get(0);
				if(user.getUsername() != null){
					usernameTx.setText(user.getUsername());
				}else{
					usernameTx.setText("未填写");
				}
				if(useraccount.getRealName() != null && !useraccount.getRealName().equals("")){
					nameEdit.setText(useraccount.getRealName());
				}else{
					nameEdit.setText("未填写");
				}
				if(useraccount.getSexTypeCode() != null){
					if(useraccount.getSexTypeCode().equals("man")){
						sexEdit.setText("男");
					}else if(useraccount.getSexTypeCode().equals("woman")){
						sexEdit.setText("女");
					}
				}else{
					usernameTx.setText("未填写");
				}
				if(useraccount.getMobilePhone() != null){
					tellphoneEdit.setText(useraccount.getMobilePhone());
				}else{
					tellphoneEdit.setText("未填写");
				}
				if(useraccount.getEmail() != null){
					emailEdit.setText(useraccount.getEmail());
				}else{
					emailEdit.setText("未填写");
				}
				showShortToast((String) msg.obj);
				break;
			case Config.HANDLER_MSG_EDITPERSON_FAIL://上传个人设置失败
				logInbar.setVisibility(View.GONE);
				showShortToast((String) msg.obj);
				break;
			
			case Config.HANDLER_MSG_UPLOAD_AVATAR_SUCCESS://上传个人头像成功
				logInbar.setVisibility(View.GONE);
				showShortToast((String) msg.obj);
				break;
			case Config.HANDLER_MSG_UPLOAD_AVATAR_FAIL://上传个人头像失败
				logInbar.setVisibility(View.GONE);
				showShortToast((String) msg.obj);
				break;
			case Config.HANDLER_MSG_DOWNLOAD_AVATAR_SUCCESS://下载个人头像成功
				user = SingleSample.getInstance(SettingAccountActivity.this).getUser();
				useraccount = user.getUseraccounts().get(0);
				if (useraccount.getAvatar() != null && !useraccount.getAvatar().equals("")) {
					imagePath11 = useraccount.getAvatar();
					imageRealPath11 = Config.IMAGE_PATH + imagePath11;
					ImageLoader.getInstance().displayImage(
							"file://" + Config.IMAGE_PATH + imagePath11,
							person_portrait_girl, options);
				}
				logInbar.setVisibility(View.GONE);
				showShortToast((String) msg.obj);
				break;
			case Config.HANDLER_MSG_DOWNLOAD_AVATAR_FAIL://下载个人头像失败
				logInbar.setVisibility(View.GONE);
				showShortToast((String) msg.obj);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_account_host);
		initData();
		initViews();
		initEvents();
	}

	private void initData(){
		user = SingleSample.getInstance(SettingAccountActivity.this)
				.getUser();
		username = user.getUsername();
		if (Tool.isNetworkAvailable(SettingAccountActivity.this)) {
		  /*if(null == user.getUseraccounts().get(0).getUserName() 
				  || user.getUseraccounts().get(0).getUserName().equals("")){
			 new Thread(getEditPersonRun).start();
		 }*/if(null == user.getUserId() 
				  || user.getUserId().equals("")){
			 new Thread(getEditPersonRun).start();
		 }
		}else{
			showShortToast("请开启网络");
		}
	}
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.ly_set_person_portrait:
			final Dialog dlg = new Dialog(this, R.style.ActionSheet);
			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			LinearLayout layout = (LinearLayout) inflater.inflate(
					R.layout.activity_writepaper_dialog, null);
			final int cFullFillWidth = 10000;
			layout.setMinimumWidth(cFullFillWidth);

			TextView mContent1 = (TextView) layout
					.findViewById(R.id.tv_content1);
			TextView mContent2 = (TextView) layout
					.findViewById(R.id.tv_content2);
			TextView mCancel = (TextView) layout.findViewById(R.id.tv_cancel);
			// 拍摄选择照片
			mContent1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String temName = DateFormat.format("yyMMdd_hhmmss",
							System.currentTimeMillis())
							+ "_" + (Math.random() * 100) + ".jpg";
					imageRealPath11 = Config.IMAGE_PATH + File.separator
							+ temName;
					File file = new File(imageRealPath11);
					if (file.exists()) {
						file.delete();
					}
					imageUri = Uri.fromFile(file);
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					startActivityForResult(intent, 1);

					dlg.dismiss();
				}
			});
			// 从相册中选择照片
			mContent2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent choosePictureIntent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					choosePictureIntent.setType("image/jpeg");
					startActivityForResult(choosePictureIntent, 2);
					dlg.dismiss();
				}
			});

			mCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					dlg.dismiss();

				}
			});

			Window w = dlg.getWindow();
			WindowManager.LayoutParams lp = w.getAttributes();
			lp.x = 0;
			final int cMakeBottom = -1000;
			lp.y = cMakeBottom;
			lp.gravity = Gravity.BOTTOM;
			dlg.onWindowAttributesChanged(lp);
			dlg.setCanceledOnTouchOutside(false);
			dlg.setContentView(layout);
			dlg.show();

			break;
		// **头像选择
		case R.id.person_portrait_girl:
			if (imagePath11.equals("")) {
				Intent intent = new Intent(this, ViewPagerActivity.class);
				// 如果初始图像地址为空，即没传数据到地址中，则把默认图像地址传进去
				intent.putExtra("image1", "drawable://"
						+ R.drawable.person_portrait_girl);
				startActivity(intent);
			}
			// 这里如果选了图像，即进行了拍照，或选取图片等操作后已经把地址传进去了
			else {
				Intent intent = new Intent(this, ViewPagerActivity.class);
				intent.putExtra("image1", "file://" + imageRealPath11);
				startActivity(intent);
			}
			;
			break;
		// 名字编辑功能
		case R.id.ly_set_name_edit:
			if(useraccount.getRealName() != null && !useraccount.getRealName().equals("")){
				Toast.makeText(this, "无须编辑", Toast.LENGTH_SHORT).show();
			}else{
				final CustomEditDialog dialog01 = new CustomEditDialog(
						SettingAccountActivity.this);
				dialog01.setTitle("编辑姓名");
				// a.getText().toString();是获取SettingAccountActivity中a当前的值；然后赋给detail
				dialog01.setDetial(nameEdit.getText().toString());
				dialog01.setLeftOnClick(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog01.dismiss();
					}
				});
				dialog01.show();
				dialog01.setRightOnClick(new OnClickListener() {
					@Override
					public void onClick(View v) {
						nameEdit.setText(dialog01.getDetial().toString());
						userRealnamestr = nameEdit.getText().toString();
						logInbar.setVisibility(View.VISIBLE);
						if (Tool.isNetworkAvailable(SettingAccountActivity.this)) {
							new Thread(postEditPersonRun).start();
						} else {
							Toast.makeText(SettingAccountActivity.this, "请设置网络", Toast.LENGTH_SHORT).show();
						}
						dialog01.dismiss();
					}
				});
				dialog01.show();
			}
			
			break;

		
		// 性别编辑暂时改为下载功能
		case R.id.ly_set_sex_edit:

			final CustomEditSexDialog dialog11 = new CustomEditSexDialog(
					SettingAccountActivity.this);
			str = sexEdit.getText() + "";
			dialog11.setDetial(str);
			dialog11.setTitle("编辑性别");
			dialog11.show();
			dialog11.setOnStateChagedListener(new OnStateChagedListener() {

				@Override
				public void onStateChanged(String str) {
					// TODO Auto-generated method stub
					sexEdit.setText(str);
					userSexstr = sexEdit.getText().toString();
					logInbar.setVisibility(View.VISIBLE);
					new Thread(postEditPersonRun).start();
					dialog11.dismiss();
				}
			});

			break;
		
		/*case R.id.ly_set_birth_edit:
			final CustomEditDialog dialog2 = new CustomEditDialog(
					SettingAccountActivity.this);
			dialog2.setTitle("编辑出生日期");
			dialog2.setDetial(birthEdit.getText().toString());
			dialog2.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
					dialog2.dismiss();
				}
			});
			dialog2.show();
			dialog2.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					birthEdit.setText(dialog2.getDetial().toString());
					userBirthstr = birthEdit.getText().toString();
					dialog2.dismiss();
				}
			});
			dialog2.show();

			break;*/
		
		case R.id.ly_set_tellphone_edit:
			final CustomEditDialog dialog3 = new CustomEditDialog(
					SettingAccountActivity.this);
			dialog3.setTitle("编辑联系电话");
			dialog3.setDetial(tellphoneEdit.getText().toString());
			dialog3.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog3.dismiss();
				}
			});
			dialog3.show();
			dialog3.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					tellphoneEdit.setText(dialog3.getDetial().toString());
					userPhonestr = tellphoneEdit.getText().toString();
					logInbar.setVisibility(View.VISIBLE);
					logInbar.setVisibility(View.VISIBLE);
					new Thread(postEditPersonRun).start();
					dialog3.dismiss();
				}
			});
			dialog3.show();
			break;
	
		case R.id.ly_set_email_edit:
			final CustomEditDialog dialog4 = new CustomEditDialog(
					SettingAccountActivity.this);
			dialog4.setTitle("编辑电子邮箱");
			dialog4.setDetial(emailEdit.getText().toString());
			dialog4.setLeftOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog4.dismiss();
				}
			});
			dialog4.show();
			dialog4.setRightOnClick(new OnClickListener() {
				@Override
				public void onClick(View v) {
					emailEdit.setText(dialog4.getDetial().toString());
					userEmailstr = emailEdit.getText().toString();
					logInbar.setVisibility(View.VISIBLE);
					new Thread(postEditPersonRun).start();
					dialog4.dismiss();
				}
			});
			dialog4.show();
			break;
	
		case R.id.titlebar_left_account_return:
			SettingCacheActivity.init_pics();
			SettingCacheActivity.init_records();
			GetFileSize g6 = new GetFileSize();
			l1 = SettingCacheActivity.l1;
			l2 = SettingCacheActivity.l2;
			k = l1 + l2;
			MainSettingFragment.init(g6.FormetFileSize(k));
			onBackPressed();
			break;
		case R.id.ly_set_account_edit_modify_password:
			Intent intent2 = new Intent();
			intent2.setClass(SettingAccountActivity.this,
					SettingAccountPasswordActivity.class);
			startActivity(intent2);
			break;
		default:
			break;
		}
	}



	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		ly_set_account_depart = (LinearLayout) findViewById(R.id.ly_set_account_depart1);
		ly_set_account_position = (LinearLayout) findViewById(R.id.ly_set_account_position1);
		ly_set_account_edit_modify_password = (LinearLayout) findViewById(R.id.ly_set_account_edit_modify_password);
		//ly_set_account_edit_modify_password.setVisibility(View.GONE);
		ly_set_name_edit = (LinearLayout) findViewById(R.id.ly_set_name_edit);
		ly_set_sex_edit = (LinearLayout) findViewById(R.id.ly_set_sex_edit);
		//ly_set_birth_edit = (LinearLayout) findViewById(R.id.ly_set_birth_edit);
		ly_set_tellphone_edit = (LinearLayout) findViewById(R.id.ly_set_tellphone_edit);
		ly_set_email_edit = (LinearLayout) findViewById(R.id.ly_set_email_edit);
		ly_set_person_portrait = (LinearLayout) findViewById(R.id.ly_set_person_portrait);
		usernameTx = (TextView)findViewById(R.id.useridtx);
		nameEdit = (EditText) findViewById(R.id.name_edit);
		sexEdit = (EditText) findViewById(R.id.sex_edit);
		//birthEdit = (EditText) findViewById(R.id.birth_edit);
		tellphoneEdit = (EditText) findViewById(R.id.tellphone_edit);
		emailEdit = (EditText) findViewById(R.id.email_edit);
		logInbar = (ProgressBar)findViewById(R.id.setting_account_progressBar);
		titlebar_left_account_return = (ImageButton) findViewById(R.id.titlebar_left_account_return);
		person_portrait_girl = (ImageView) findViewById(R.id.person_portrait_girl);
		nameEdit = (EditText) findViewById(R.id.name_edit);
		sexEdit = (EditText) findViewById(R.id.sex_edit);
		//birthEdit = (EditText) findViewById(R.id.birth_edit);
		tellphoneEdit = (EditText) findViewById(R.id.tellphone_edit);
		emailEdit = (EditText) findViewById(R.id.email_edit);
		set_account_position_who = (TextView) findViewById(R.id.set_account_position_who);
		set_account_depart = (TextView) findViewById(R.id.setting_departTv);
		ly_set_account_depart.setVisibility(View.GONE);
		ly_set_account_position.setVisibility(View.GONE);
		// ButtonListener buttonListener =new ButtonListener();
		// 根据任务类型来显示部门，职位，修改密码
		user = SingleSample.getInstance(SettingAccountActivity.this).getUser();
		
		
		
		if(user.getUseraccounts()!=null && !user.getUseraccounts().isEmpty()){
			
			if(user.getUseraccounts().get(0) != null){
				useraccount = user.getUseraccounts().get(0);
				if(useraccount.getAvatar() != null && !useraccount.getAvatar().equals("")){
					if (Tool.isNetworkAvailable(SettingAccountActivity.this)) {
						new Thread(downloadAvatarRun).start();
					} else {
						Toast.makeText(SettingAccountActivity.this, "请设置网络", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(SettingAccountActivity.this, "还未设置头像", Toast.LENGTH_SHORT).show();
				}
				if(user.getUsername() != null){
					usernameTx.setText(user.getUsername());
				}else{
					usernameTx.setText("未填写");
				}
				if(useraccount.getRealName() != null){
					nameEdit.setText(useraccount.getRealName());
				}else{
					nameEdit.setText("未填写");
				}
				if(useraccount.getSexTypeCode() != null){
					if(useraccount.getSexTypeCode().equals("man")){
						sexEdit.setText("男");
					}else if(useraccount.getSexTypeCode().equals("woman")){
						sexEdit.setText("女");
					}
				}else{
					sexEdit.setText("男");
				}
				if(useraccount.getMobilePhone() != null){
					tellphoneEdit.setText(useraccount.getMobilePhone());
				}else{
					tellphoneEdit.setText("未填写");
				}
				if(useraccount.getEmail() != null){
					emailEdit.setText(useraccount.getEmail());
				}else{
					emailEdit.setText("未填写");
				}
				if(useraccount.getDepartment() != null){
					ly_set_account_depart.setVisibility(View.VISIBLE);
					set_account_depart.setText(useraccount.getDepartment());
					//ly_set_account_edit_modify_password.setVisibility(View.GONE);
				}else{
					ly_set_account_depart.setVisibility(View.GONE);
				}if(useraccount.getRoleName() != null){
					ly_set_account_position.setVisibility(View.VISIBLE);
					set_account_position_who.setText(useraccount.getRoleName());
				}else{
					ly_set_account_position.setVisibility(View.GONE);
				}
				/*if (user_type.equals(Config.USER_HOUSE_USER)) {
					ly_set_account_depart.setVisibility(View.GONE);
					ly_set_account_position.setVisibility(View.GONE);
					ly_set_account_edit_modify_password.setVisibility(View.VISIBLE);
				} else if (user_type.equals(Config.USER_LEAFLET_DISTRIBUTOR)) {
					ly_set_account_depart.setVisibility(View.VISIBLE);
					ly_set_account_position.setVisibility(View.VISIBLE);
					ly_set_account_edit_modify_password.setVisibility(View.GONE);
				} else if (user_type.equals(Config.USER_SERVICE_PERSON)) {
					ly_set_account_depart.setVisibility(View.VISIBLE);
					ly_set_account_position.setVisibility(View.VISIBLE);
					set_account_position_who.setText("服务人员");
					ly_set_account_edit_modify_password.setVisibility(View.GONE);
				}*/
				
				//birthEdit.setText("未填写");
			}else{
				usernameTx.setText("未填写");
				nameEdit.setText("未填写");
				sexEdit.setText("男");
				tellphoneEdit.setText("未填写");
				emailEdit.setText("未填写");
				//birthEdit.setText("未填写");
				Toast.makeText(SettingAccountActivity.this, "未获取用户信息", Toast.LENGTH_SHORT).show();
			}
		}else{
			usernameTx.setText("未填写");
			nameEdit.setText("未填写");
			sexEdit.setText("男");
			tellphoneEdit.setText("未填写");
			emailEdit.setText("未填写");
			//birthEdit.setText("未填写");
			Toast.makeText(SettingAccountActivity.this, "未获取用户信息", Toast.LENGTH_SHORT).show();
		}
		userRealnamestr = nameEdit.getText().toString();
		userSexstr = sexEdit.getText().toString();
		//userBirthstr = birthEdit.getText().toString();
		userPhonestr = tellphoneEdit.getText().toString();
		userEmailstr = emailEdit.getText().toString();
		
		
	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		/* titlebar_right_account_edit.setOnClickListener(this); */
		titlebar_left_account_return.setOnClickListener(this);
		ly_set_account_edit_modify_password.setOnClickListener(this);
		ly_set_name_edit.setOnClickListener(this);
		ly_set_sex_edit.setOnClickListener(this);
		//ly_set_birth_edit.setOnClickListener(this);
		ly_set_tellphone_edit.setOnClickListener(this);
		ly_set_email_edit.setOnClickListener(this);
		sexEdit.setOnClickListener(this);
		//birthEdit.setOnClickListener(this);
		tellphoneEdit.setOnClickListener(this);
		emailEdit.setOnClickListener(this);
		set_account_position_who.setOnClickListener(this);
		person_portrait_girl.setOnClickListener(this);
		ly_set_person_portrait.setOnClickListener(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			Bundle b = new Bundle();
			b.putString("imagePath", imageRealPath11);
			Intent intent = new Intent(SettingAccountActivity.this,
					ChoosephotoActivity.class);
			flag = 1;
			intent.putExtras(b);
			startActivityForResult(intent, 3);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
			Bundle bundle = new Bundle();
			Uri uri = data.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Log.e("picture", uri.toString());
			Cursor cursor = getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			imageRealPath11 = cursor.getString(columnIndex);
			cursor.close();
			bundle.putString("imagePath", imageRealPath11);
			Intent intent = new Intent(SettingAccountActivity.this,
					ChoosephotoActivity.class);
			flag = 2;
			intent.putExtras(bundle);
			startActivityForResult(intent, 3);
		}

		
		else if (resultCode == Activity.RESULT_OK && requestCode == 3) {
			imagePath11 = data.getStringExtra("imagePath");
			imageRealPath11 = Config.IMAGE_PATH + imagePath11;
		}
		if (!imagePath11.equals("")) {

			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + imagePath11,
					person_portrait_girl, options);
			useraccount.setAvatar(imagePath11);
			useraccount.update(useraccount.getId());
			/*user.setUseraccount(useraccount);
			user.update(user.getId());*/
			if (Tool.isNetworkAvailable(SettingAccountActivity.this)) {
				logInbar.setVisibility(View.VISIBLE);
				new Thread(uploadAvatarRun).start();
			} else {
				Toast.makeText(SettingAccountActivity.this, "请设置网络", Toast.LENGTH_SHORT).show();
			}

		}
		
	}
	
	// 获取个人信息
	Runnable getEditPersonRun = new Runnable() {

			@Override
		public void run() {
				// TODO Auto-generated method stub
			Tool.getEditPerson(SettingAccountActivity.this);
		}
	};
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			/*SettingCacheActivity.init_pics();
			SettingCacheActivity.init_records();
			GetFileSize g6 = new GetFileSize();
			l1 = SettingCacheActivity.l1;
			l2 = SettingCacheActivity.l2;
			k = l1 + l2;
			// clean_all.setText("一键清除所有（"+g6.FormetFileSize(k)+")");
			MainSettingFragment.init(g6.FormetFileSize(k));*/
			onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	//上传个人设置
	Runnable postEditPersonRun = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			postEditPerson();
		}
	};
	// 上传个人设置
		private void postEditPerson() {
			if (Tool.isNetworkAvailable(SettingAccountActivity.this)) {
				try {
					String url = Tool.getConfigUrl(Config.SERVER_URL, Config.EDIT_PERSON_URL);
					String result = null;
					Map<String, String> map = new HashMap<String, String>();
					String usersexTypeCode = "";
					if(userSexstr.equals("男")){
						usersexTypeCode = "man";
						
					}else{
						usersexTypeCode = "woman";
						
					}
					map.put("realName", userRealnamestr);
					map.put("sexTypeCode", usersexTypeCode);
					map.put("mobilePhone", userPhonestr);
					map.put("email", userEmailstr);
					String setsessionid = "";
					user = SingleSample.getInstance(SettingAccountActivity.this).getUser();
					if(null != user){
						if(null != user.getSessionId() && !user.getSessionId().equals("")){
							setsessionid = user.getSessionId();
						}
					}
					result = HttpUtil.postRequestSe(url, map,setsessionid);
					Log.e("上传个人设置的result", result);
					String message = new JSONObject(result).getString("message");
					String flag = new JSONObject(result).getString("flag");
					if (flag.equals(Config.CONNECT_SUCCESS2)) {
						useraccount.setRealName(userRealnamestr);
						useraccount.setSexTypeCode(usersexTypeCode);
						useraccount.setMobilePhone(userPhonestr);
						useraccount.setEmail(userEmailstr);
						useraccount.update(useraccount.getId());
						/*user.setUseraccount(useraccount);
						user.update(user.getId());*/
						
						mHandler.obtainMessage(
								Config.HANDLER_MSG_EDITPERSON_SUCCESS, message)
								.sendToTarget();// 通知主线程数据发送成功

					}else{
						mHandler.obtainMessage(
								Config.HANDLER_MSG_EDITPERSON_FAIL, message)
								.sendToTarget();// 通知主线程数据发送失败
					}

				} catch (Exception e) {
					
					Log.e("ServiceScheduleActivity", "json数据获取报错");
					mHandler.obtainMessage(
							Config.HANDLER_MSG_EDITPERSON_FAIL, "json数据获取报错")
							.sendToTarget();// 通知主线程数据发送失败
					e.printStackTrace();
				}
			}else {

				String message = "请设置网络";
				mHandler.obtainMessage(Config.HANDLE_MSG_SEARCH_FAIL,
						message).sendToTarget();

				/* start = ++refreshCnt; */
			}
		}
		
		// 上传文件
		// From: CheckTaskDetailActivity
		private Runnable uploadAvatarRun = new Runnable() {

			@Override
			public void run() {
				String url = Tool.getConfigUrl(Config.SERVER_URL, Config.UPLOAD_AVATAR_URL);
				String result = "";
				String flagstr = "";
				String message = "";
				Map<String, String> params = new HashMap<String, String>();
				ArrayList<File> files = new ArrayList<File>();
				String imagepath1 = Config.IMAGE_PATH + imagePath11;
				File file1;

				if (!imagepath1.equals("")) {
					file1 = new File(imagepath1);
					if (file1.exists()) {
						files.add(file1);
					}
				}
				
				System.out.println(files.size());

				if (files.size() > 0 && !files.isEmpty()) {
					params.put("sessionId", user.getSessionId());
					UploadService uploadService = new UploadService();

					try {
						result = uploadService.uploadFileswithNon(url, params, files);
						Log.e("头像文件上传的result", result);
						JSONObject jsonobg= new JSONObject(result);

						System.out.println("result:" + result);
						flagstr = jsonobg.getString("flag");
						flagstr = jsonobg.getString("message");
						if (flagstr.equals(Config.CONNECT_SUCCESS2)) {
							useraccount.setAvatar(imagePath11);
							useraccount.update(useraccount.getId());
							mHandler.obtainMessage(
									Config.HANDLER_MSG_UPLOAD_AVATAR_SUCCESS, message)
									.sendToTarget();// 通知主线程数据发送成功

						}else{
							mHandler.obtainMessage(
									Config.HANDLER_MSG_UPLOAD_AVATAR_FAIL, message)
									.sendToTarget();// 通知主线程数据发送失败
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("c超时", "c超时");
						mHandler.obtainMessage(
								Config.HANDLER_MSG_UPLOAD_AVATAR_FAIL, "json数据获取报错")
								.sendToTarget();// 通知主线程数据发送失败
					} catch (Exception e) {
						e.printStackTrace();
						Log.e("s超时", "s超时");
						mHandler.obtainMessage(
								Config.HANDLER_MSG_UPLOAD_AVATAR_FAIL, "数据传输报错")
								.sendToTarget();// 通知主线程数据发送失败
					}

					
				} else {
					
				}

			}

		};
		
		// 下载文件
				// From: CheckTaskDetailActivity
				private Runnable downloadAvatarRun = new Runnable() {

					@Override
					public void run() {
						String urlstr = Tool.getConfigUrl(Config.SERVER_URL, Config.DOWNLOAD_AVATAR_URL);
						boolean flagb = false;
						Map<String, String> map = new HashMap<String, String>();
						
								map.put("sessionId", user.getSessionId());
								map.put("fileName", useraccount.getAvatar());
								if (null != useraccount.getAvatar()
										&& !useraccount.getAvatar().equals("")) {
									try {
										flagb = UploadService.downFilewithNon(urlstr,
												Config.IMAGE_PATH, map);
										if (flagb) {
											/*user.setAvatarImagePath(imagePath11);
											user.update(user.getId());*/
											mHandler.obtainMessage(
													Config.HANDLER_MSG_DOWNLOAD_AVATAR_SUCCESS, "头像下载成功")
													.sendToTarget();// 通知主线程数据发送成功

										}else{
											mHandler.obtainMessage(
													Config.HANDLER_MSG_DOWNLOAD_AVATAR_FAIL, "头像下载失败")
													.sendToTarget();// 通知主线程数据发送失败
										}
									} catch (ClientProtocolException e) {
										// TODO Auto-generated catch block
										mHandler.obtainMessage(
												Config.HANDLER_MSG_DOWNLOAD_AVATAR_FAIL, "头像下载失败")
												.sendToTarget();// 通知主线程数据发送失败
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										mHandler.obtainMessage(
												Config.HANDLER_MSG_DOWNLOAD_AVATAR_FAIL, "头像下载失败")
												.sendToTarget();// 通知主线程数据发送失败
										e.printStackTrace();
									}
								}

					}

				};
			
		
}
